<?php

namespace seecms\lib;

use seecms\lib\provider\General;
use seecms\lib\provider\Upload;
use seecms\lib\provider\User;
use seecms\lib\provider\UserLogin;
use seecms\SeeConfig;
use seecms\SeeException;

/**
 * @property User $user
 * @property UserLogin $user_login
 * @property Upload $upload
 * @property General $general
 */
class Provider
{

    /**
     * @throws SeeException
     */
    public function __get($property)
    {
        return $this->getExtensionClass($property);
    }

    /**
     * @param $name
     * @return mixed|null
     * @throws SeeException
     */
    protected function getExtensionClass($name)
    {
        $extensions = [
            // 用户登录
            'user_login' => UserLogin::class,
            // 用户信息
            'user' => User::class,
            // 通用设置
            'general' => General::class,
            // 上传设置
            'upload' => Upload::class
        ];

        $extensions = array_merge($extensions, SeeConfig::instance()->provider->config);

        $namespace = $extensions[$name] ?? '';

        if (empty($namespace)) {
            SeeException::throw('尚未配置' . $name . '扩展');
        }

        $class = null;
        $message = '';
        try {
            if (class_exists($namespace)) {
                $class = new $namespace();
            }
        } catch (\Exception $exception) {
            $message = $exception->getMessage();
        }

        if ($message) {
            SeeException::throw($message);
        }

        return $class;
    }
}